package com.flyduck.vueshop.common.feign.interceptor;

import cn.dev33.satoken.context.SaHolder;
import cn.dev33.satoken.context.model.SaRequest;
import cn.dev33.satoken.same.SaSameUtil;
import cn.dev33.satoken.stp.StpUtil;
import com.flyduck.vueshop.common.core.constant.CommonConstant;
import feign.RequestInterceptor;
import feign.RequestTemplate;
import org.springframework.stereotype.Component;

/**
 * @program: vueshop-cloud
 * @description:
 * @author: flyduck
 * @create: 2024-07-07 08:07
 **/
@Component
public class FeignRequestInterceptor implements RequestInterceptor {
    @Override
    public void apply(RequestTemplate requestTemplate) {
        //将用户信息携带过去
        if(SaHolder.getContext().isValid()){
            SaRequest request = SaHolder.getRequest();
            requestTemplate.header(CommonConstant.TokenHeaderConstant.ADMIN_TOKEN_NAME, request.getHeader(CommonConstant.TokenHeaderConstant.ADMIN_TOKEN_NAME,null));
            requestTemplate.header(CommonConstant.TokenHeaderConstant.USER_TOKEN_NAME, request.getHeader(CommonConstant.TokenHeaderConstant.USER_TOKEN_NAME,null));
        }

        //防止用户不经过网关直接访问微服务：feign调用携带same-token
        requestTemplate.header(SaSameUtil.SAME_TOKEN, SaSameUtil.getToken());
        //feign接口直接内部服务调用，外部不能直接调用，feign调用必须加上头 sa-source => sa-inner，拦截器里面通过这个判断是否为内部请求
        requestTemplate.header(CommonConstant.SaSourceConstant.SA_SOURCE_KEY, CommonConstant.SaSourceConstant.SA_SOURCE_KEY_INNER);
    }
}
